from PyQt5.QtWidgets import (QWidget, QVBoxLayout, QPushButton, 
                           QTableWidget, QTableWidgetItem, QHeaderView,
                           QMessageBox, QHBoxLayout, QComboBox, QLabel)
from PyQt5.QtCore import Qt, QTimer
from datetime import datetime
import requests
import asyncio
from core.platform_auth import platform_auth
from core.platform_config import platform_config

class PersonManagePage(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.current_page = 1  # 当前页码
        self.total_pages = 1   # 总页数
        self.page_size = 10    # 每页显示数量
        self.setup_ui()
        
    def setup_ui(self):
        layout = QVBoxLayout(self)
        
        # 一键删除过期人员按钮
        delete_btn = QPushButton("一键删除过期人员")
        delete_btn.clicked.connect(self.delete_expired_persons)
        layout.addWidget(delete_btn)
        
        # 人员列表
        self.table = QTableWidget()
        self.table.setColumnCount(7)
        self.table.setHorizontalHeaderLabels([
            "姓名", "部门", "身份证号", "卡号", "有效期开始", "有效期结束", "状态"
        ])
        
        # 设置表格样式
        header = self.table.horizontalHeader()
        for i in range(7):
            header.setSectionResizeMode(i, QHeaderView.ResizeMode.ResizeToContents)
        
        layout.addWidget(self.table)
        
        # 添加分页控件
        page_layout = QHBoxLayout()
        
        # 上一页按钮
        self.prev_btn = QPushButton("上一页")
        self.prev_btn.clicked.connect(self.prev_page)
        page_layout.addWidget(self.prev_btn)
        
        # 页码显示
        self.page_label = QLabel("第 1 页 / 共 1 页")
        page_layout.addWidget(self.page_label)
        
        # 下一页按钮
        self.next_btn = QPushButton("下一页")
        self.next_btn.clicked.connect(self.next_page)
        page_layout.addWidget(self.next_btn)
        
        # 每页显示数量选择
        page_size_layout = QHBoxLayout()
        page_size_layout.addWidget(QLabel("每页显示:"))
        self.page_size_combo = QComboBox()
        self.page_size_combo.addItems(["10", "20", "50", "100"])
        self.page_size_combo.currentTextChanged.connect(self.on_page_size_changed)
        page_size_layout.addWidget(self.page_size_combo)
        page_layout.addLayout(page_size_layout)
        
        # 跳转页面
        goto_layout = QHBoxLayout()
        goto_layout.addWidget(QLabel("跳转到:"))
        self.goto_page_combo = QComboBox()
        self.goto_page_combo.currentTextChanged.connect(self.on_goto_page)
        goto_layout.addWidget(self.goto_page_combo)
        page_layout.addLayout(goto_layout)
        
        # 刷新按钮
        refresh_btn = QPushButton("刷新列表")
        refresh_btn.clicked.connect(self.refresh_list)
        page_layout.addWidget(refresh_btn)
        
        layout.addLayout(page_layout)
        
        # 使用定时器延迟初始化
        QTimer.singleShot(0, self.delayed_init)
        
    def update_pagination_controls(self, total_rows: int):
        """更新分页控件状态"""
        self.total_pages = (total_rows + self.page_size - 1) // self.page_size
        self.page_label.setText(f"第 {self.current_page} 页 / 共 {self.total_pages} 页")
        
        # 更新页码下拉框
        self.goto_page_combo.clear()
        self.goto_page_combo.addItems([str(i) for i in range(1, self.total_pages + 1)])
        self.goto_page_combo.setCurrentText(str(self.current_page))
        
        # 更新按钮状态
        self.prev_btn.setEnabled(self.current_page > 1)
        self.next_btn.setEnabled(self.current_page < self.total_pages)
        
    def prev_page(self):
        """上一页"""
        if self.current_page > 1:
            self.current_page -= 1
            self.refresh_list()
            
    def next_page(self):
        """下一页"""
        if self.current_page < self.total_pages:
            self.current_page += 1
            self.refresh_list()
            
    def on_page_size_changed(self, size: str):
        """改变每页显示数量"""
        self.page_size = int(size)
        self.current_page = 1  # 重置到第一页
        self.refresh_list()
        
    def on_goto_page(self, page: str):
        """跳转到指定页"""
        if page and page.isdigit():
            page_num = int(page)
            if 1 <= page_num <= self.total_pages and page_num != self.current_page:
                self.current_page = page_num
                self.refresh_list()
        
    def delayed_init(self):
        """延迟初始化，等待事件循环启动"""
        try:
            # 同步方式获取token
            if not platform_auth.token:
                # 创建一个新的事件循环来运行异步初始化
                loop = asyncio.new_event_loop()
                asyncio.set_event_loop(loop)
                loop.run_until_complete(platform_auth.initialize())
                loop.close()
            
            # 初始化完成后加载数据
            self.refresh_list()
            
        except Exception as e:
            QMessageBox.critical(self, "错误", f"初始化失败: {str(e)}")
        
    def refresh_list(self):
        try:
            if not platform_auth.token:
                raise Exception("认证token未初始化")
                
            base_url = platform_config.dahua.api_host
            url = f"{base_url}/evo-apigw/evo-brm/1.2.0/person/page"
            
            headers = {
                'accept': 'application/json, text/plain, */*',
                'content-type': 'application/json;charset=UTF-8',
                'authorization': f'bearer {platform_auth.token}',
                'User-Client': '1'
            }
            
            data = {
                "searchKey": "",
                "pageNum": self.current_page,
                "pageSize": self.page_size,
                "departmentId": 1,
                "isContain": True,
                "statusList": [1, 2]
            }
            
            response = requests.post(url, json=data, headers=headers, verify=False)
            result = response.json()
            
            # 检查返回结果的结构
            if not isinstance(result, dict):
                raise Exception(f"返回数据格式错误: {result}")
                
            if not result.get("success"):
                raise Exception(f"API调用失败: {result.get('errMsg', '未知错误')}")
                
            if "data" not in result or "pageData" not in result["data"]:
                raise Exception(f"返回数据结构错误: {result}")
            
            # 更新分页信息
            total_rows = result["data"].get("totalRows", 0)
            self.update_pagination_controls(total_rows)
            
            # 清空表格
            self.table.setRowCount(0)
            
            # 填充数据
            for person in result["data"]["pageData"]:
                row = self.table.rowCount()
                self.table.insertRow(row)
                
                # 获取主卡号
                card_number = ""
                for card in person.get("cards", []):
                    if card.get("isMainCard") == 1:
                        card_number = card.get("cardNumber", "")
                        break
                
                # 设置表格数据
                name_item = QTableWidgetItem(str(person.get("name", "")))
                name_item.setData(Qt.ItemDataRole.UserRole, person.get("id"))  # 保存ID到用户数据
                self.table.setItem(row, 0, name_item)
                self.table.setItem(row, 1, QTableWidgetItem(str(person.get("departmentName", ""))))
                self.table.setItem(row, 2, QTableWidgetItem(str(person.get("paperNumber", ""))))
                self.table.setItem(row, 3, QTableWidgetItem(str(card_number)))
                self.table.setItem(row, 4, QTableWidgetItem(str(person.get("validStartTime", ""))))
                self.table.setItem(row, 5, QTableWidgetItem(str(person.get("validEndTime", ""))))
                self.table.setItem(row, 6, QTableWidgetItem("正常" if person.get("status") == 1 else "禁用"))
                
                # 设置单元格文本居中对齐
                for col in range(7):
                    item = self.table.item(row, col)
                    if item:
                        item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
                
        except Exception as e:
            QMessageBox.critical(self, "错误", f"获取人员列表失败: {str(e)}")
            
    def delete_expired_persons(self):
        try:
            if not platform_auth.token:
                raise Exception("认证token未初始化")
            
            # 1. 获取当前时间
            current_time = datetime.now()
            
            # 2. 直接从当前表格获取数据并找出过期的人员
            expired_rows = []  # 存储过期行的索引
            expired_ids = []   # 存储过期人员的ID
            
            for row in range(self.table.rowCount()):
                try:
                    # 获取有效期结束时间
                    end_time_str = self.table.item(row, 5).text()  # 第6列是有效期结束时间
                    end_time = datetime.strptime(end_time_str, "%Y-%m-%d %H:%M:%S")
                    
                    if end_time < current_time:
                        expired_rows.append(row)
                        # 这里需要添加一个隐藏列存储ID，或者从数据源中获取ID
                        person_id = self.table.item(row, 0).data(Qt.ItemDataRole.UserRole)  # 从单元格的用户数据中获取ID
                        if person_id:
                            expired_ids.append(person_id)
                except (ValueError, AttributeError):
                    continue
            
            if not expired_ids:
                QMessageBox.information(self, "提示", "没有找到过期人员")
                return
            
            # 添加确认对话框
            reply = QMessageBox.question(
                self,
                "确认删除",
                f"确定要删除 {len(expired_ids)} 个过期人员吗？",
                QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
                QMessageBox.StandardButton.No
            )
            
            if reply == QMessageBox.StandardButton.No:
                return
            
            # 3. 调用删除接口
            base_url = platform_config.dahua.api_host
            delete_url = f"{base_url}/evo-apigw/evo-brm/1.2.0/person/delete"
            headers = {
                'accept': 'application/json, text/plain, */*',
                'content-type': 'application/json;charset=UTF-8',
                'authorization': f'bearer {platform_auth.token}',
                'User-Client': '1',
                'accept-language': 'zh-CN',
                'timeoffset': '-28800000'
            }
            
            delete_data = {
                "openDeleteFlag": 1,
                "deleteCardFlag": 1,
                "departmentId": 1,
                "ids": expired_ids
            }
            
            delete_response = requests.post(
                delete_url, 
                json=delete_data,
                headers=headers,
                verify=False
            )
            delete_result = delete_response.json()
            
            if not delete_result.get("success"):
                raise Exception(f"删除失败: {delete_result.get('errMsg', '未知错误')}")
            
            # 4. 从表格中移除过期行（从后往前删除，避免索引变化）
            for row in sorted(expired_rows, reverse=True):
                self.table.removeRow(row)
            
            QMessageBox.information(
                self, 
                "成功", 
                f"已删除 {len(expired_ids)} 个过期人员"
            )
            
        except Exception as e:
            QMessageBox.critical(self, "错误", f"删除过期人员失败: {str(e)}") 